package com.sky.zzh.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapFactory;
import android.util.Log;

public class HttpUtils {

	public static String submitPostImg(String address, String imgfile) {

		Log.i("ccc", "address:" + address);
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(address); // 转化成URL格式
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(18000); // 设置连接超时时间
			httpURLConnection.setDoInput(true); // 打开输入流，以便从服务器获取数据
			httpURLConnection.setDoOutput(true); // 打开输出流，以便向服务器提交数据
			httpURLConnection.setRequestMethod("POST"); // 设置以Post方式提交数据
			httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存
			// 设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("AccessToken", "123456789");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// httpURLConnection.setRequestProperty("Content-Type",
			// "application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;image/png");
			// 设置请求体的长度
			// httpURLConnection.setRequestProperty("Content-Length",
			// String.valueOf(data.length));
			// 获得输出流，向服务器写入数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			// outputStream.write(data);
			// Log.i("aaa", "data" + httpURLConnection.get);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(outputStream);

//			StringBuffer stringBuffer = new StringBuffer(); // 存储封装好的请求体信息
//			for (Map.Entry<String, String> entry : params.entrySet()) {
//				stringBuffer
//						.append(twoHyphens + boundary + end)
//						.append("Content-Disposition: form-data; name=\""
//								+ entry.getKey() + "\"\r\n\r\n")
//						.append(entry.getValue() + "\r\n");
//			}
//			ds.write(stringBuffer.toString().getBytes());

			// add file
//			ds.writeBytes(twoHyphens + boundary + end);
//			ds.writeBytes("Content-Disposition: form-data; "
//					+ "name=\"" + "uploadImg" + "\";filename=\""
//					+ "uploadImg.png\"" + end);
//			ds.writeBytes("Content-Type: application/octet-stream; charset="
//                    + "utf-8" + end);
//			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgfile, opts);
			opts.inSampleSize = calcSampleSize(opts, 300, 300);
			opts.inJustDecodeBounds = false;
			opts.inPurgeable = true;
			opts.inInputShareable = true;
			Bitmap bit = BitmapFactory.decodeFile(imgfile, opts);
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			int quality = 90;
			bit.compress(CompressFormat.PNG, quality, bout);
//			if (bout.toByteArray().length > 1024 * 100) {
//				bout.reset();
//				quality -= 10;
//				bit.compress(CompressFormat.PNG, quality, bout);
//			}
			ds.write(bout.toByteArray());
			ds.writeBytes(end);
			bout.close();
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			ds.flush();
			/* 关闭DataOutputStream */
			ds.close();

			int response = httpURLConnection.getResponseCode();// 获得服务器的响应码
			Log.i("HTTP:SubmitImg", response+"");
			Log.i("ccc", "result : " + response);
			if (response == HttpURLConnection.HTTP_OK) {
				Log.i("ccc", "inptStream");
				InputStream inptStream = httpURLConnection.getInputStream();
				return dealResponseResult(inptStream); // 处理服务器的响应结果
			}
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("ccc", e.toString());
		}
		
		
//        try
//        {
//          URL url =new URL(address);
//          HttpURLConnection con=(HttpURLConnection)url.openConnection();
//          /* 允许Input、Output，不使用Cache */
//          con.setDoInput(true);
//          con.setDoOutput(true);
//          con.setUseCaches(false);
//          /* 设置传送的method=POST */
//          con.setRequestMethod("POST");
//          /* setRequestProperty */
//          con.setRequestProperty("Connection", "Keep-Alive");
//          con.setRequestProperty("Charset", "UTF-8");
//          con.setRequestProperty("Content-Type",
//                             "multipart/form-data;boundary="+boundary);
//          /* 设置DataOutputStream */
//          DataOutputStream ds =
//            new DataOutputStream(con.getOutputStream());
//          ds.writeBytes(twoHyphens + boundary + end);
//          ds.writeBytes("Content-Disposition: form-data; "+
//                        "name=\"file1\";filename=\""+
//                        "photo.jpg" +"\""+ end);
//          ds.writeBytes(end);  
//          /* 取得文件的FileInputStream */
//          FileInputStream fStream =new FileInputStream(imgfile);
//          /* 设置每次写入1024bytes */
//          int bufferSize =1024;
//          byte[] buffer =new byte[bufferSize];
//          int length =-1;
//          /* 从文件读取数据至缓冲区 */
//          while((length = fStream.read(buffer)) !=-1)
//          {
//            /* 将资料写入DataOutputStream中 */
//            ds.write(buffer, 0, length);
//          }
//          ds.writeBytes(end);
//          ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
//          /* close streams */
//          fStream.close();
//          ds.flush();
//          /* 取得Response内容 */
//          InputStream is = con.getInputStream();
//          int ch;
//          StringBuffer b =new StringBuffer();
//          while( ( ch = is.read() ) !=-1 )
//          {
//            b.append( (char)ch );
//          }
//          /* 将Response显示于Dialog */
//          Log.i("aaa", "上传成功"+b.toString().trim());
//          /* 关闭DataOutputStream */
//          ds.close();
//        }
//        catch(Exception e)
//        {
//          Log.i("aaa", "上传失败"+e);
//        }
		
		return "";
	}

	public static String uploadImage(String url,File f) {  
//	    HttpClient httpClient = new DefaultHttpClient();  
//	    HttpPost httpPost = new HttpPost(url);  
//	    System.out.println("url:"+url);
//	    try {  
//	        // 需要上传的文件  
//	        String root = "D:/api/";  
//	        String fileName = "JDK6.0 中文文档.CHM";  
//	        File uploadFile = new File(root+fileName);  
//	        //定义FileEntity对象  
//	        HttpEntity entity = new FileEntity(f, "image/png") ;
//	        //为httpPost设置头信息  
////	        httpPost.setHeader("filename", URLEncoder.encode(fileName,"utf-8"));//服务器可以读取到该文件名  
//	        httpPost.addHeader("AccessToken", "123456789");
//	        httpPost.addHeader("Content-Type","multipart/form-data;boundary=" + "*****");
////	        httpPost.addHeader("Content-Length", String.valueOf(entity.getContentLength()));//设置传输长度  
//	        httpPost.setEntity(entity);
//	          
//	        // httpClient执行httpPost提交  
//	        HttpResponse response = httpClient.execute(httpPost);  
//	        // 得到服务器响应实体对象  
//	        System.out.println("code:"+response.getStatusLine().getStatusCode());
//	        HttpEntity responseEntity = response.getEntity();  
//	        if (responseEntity != null) {  
//	            System.out.println(EntityUtils.toString(responseEntity, "utf-8"));  
//	            System.out.println("文件 "+fileName+"上传成功！");  
//	        } else {  
//	            System.out.println("服务器无响应！");  
//	        }  
//	    } catch (Exception e) {  
//	        e.printStackTrace();  
//	    } finally {  
//	        // 释放资源  
//	        httpClient.getConnectionManager().shutdown();  
//	    }  
		
		
		HttpClient httpclient = new DefaultHttpClient();  
        
        try {  
//            BufferedReader in = new BufferedReader(new FileReader("config/actionUrl.properties"));  
//            String actionUrl;  
//            actionUrl = in.readLine();  
            HttpPost httppost = new HttpPost(url);  
              
            // 通过阅读源码可知，要想实现图片上传功能，必须将 MultipartEntity 的模式设置为 BROWSER_COMPATIBLE 。  
            MultipartEntity multiEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
//            MultipartEntity multiEntity = new MultipartEntity();  
              
            // 读取图片的 MIME Type 类型集  
            Properties mimeTypes = new Properties();  
            mimeTypes.load(new FileInputStream(new File("config/MIMETypes.properties")));  
              
            // 构造图片数据  
            Properties imageParams = new Properties();  
            imageParams.load(new FileInputStream(new File("config/imageParams.properties")));  
            String fileType;  
            for(Map.Entry<Object,Object> image : imageParams.entrySet()) {  
                String path = image.getValue().toString();  
                fileType = path.substring(path.lastIndexOf(".") + 1);  
                FileBody binaryContent = new FileBody(new File(path), mimeTypes.get(fileType).toString());  
//                FileBody binaryContent = new FileBody(new File(path));  
                multiEntity.addPart(image.getKey().toString(), binaryContent);  
            }  
              
            // 构造表单参数数据  
            Properties formDataParams = new Properties();  
            formDataParams.load(new FileInputStream(new File("config/formDataParams.properties")));  
            for(Entry<Object, Object> param : formDataParams.entrySet()) {  
                multiEntity.addPart(param.getKey().toString(), new StringBody(param.getValue().toString()));  
            }  
            httppost.addHeader("AccessToken", "123456789");
            httppost.setEntity(multiEntity);  
//            Out.println("executing request " + httppost.getRequestLine());  
              
            HttpResponse response = httpclient.execute(httppost);  
            HttpEntity resEntity = response.getEntity();  
            System.out.println("code:"+response.getStatusLine().getStatusCode());  
//            Out.println("-------------------");  
//            Out.println(response.getStatusLine());  
            if(resEntity != null) {  
                String returnContent = EntityUtils.toString(resEntity);  
                return returnContent; // 返回页面内容  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 释放资源  
            httpclient.getConnectionManager().shutdown();  
        }  
        return null;  
	}
	
	private static int calcSampleSize(Options opts, int i, int j) {
		int width = opts.outWidth;
		int height = opts.outHeight;
		int sampleSize=1;
		if (width > i && height > j) {
			int widthScale=Math.round((float)width/(float)i);
			int heightScale=Math.round((float)height/(float)j);
			sampleSize=Math.max(widthScale, heightScale);
		}
		return sampleSize;
	}
	
	/*
	 * Function : 处理服务器的响应结果（将输入流转化成字符串） Param : inputStream服务器的响应输入流
	 */
	public static String dealResponseResult(InputStream inputStream) {
		String resultData = null; // 存储处理结果
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("ccc", "dealResponseResult" + e.toString());
		}
		resultData = new String(byteArrayOutputStream.toByteArray());
		return resultData;
	}

}
